package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BaseBusinessException;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.QueryMemberRequest;
import com.mall.user.dto.QueryMemberResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ciggar
 * create-date: 2019/8/1-下午4:47
 */
@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Reference(check = false)
    private IMemberService memberService;


    // 查库存
    @Autowired
    private StockMapper stockMapper;

    /**
     * 验证用户合法性
     *
     * @return
     */

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 向下转型
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //
        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        // 商品Id
        List<Long> productIds = createOrderContext.getBuyProductIds();
        // 如果为空，进行赋值
        if (CollectionUtils.isEmpty(productIds)){
//            for (CartProductDto cartProductDto : dtoList) {
//                Long productId = cartProductDto.getProductId();
//                productIds.add(productId);//100040607
//            }

            //lambda表达式：获取到流，声明对象u，从而拿到Id
            productIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
        }
        //排序
        //productIds.sort(Long::compareTo);

        //锁定库存
        List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);

//        if (CollectionUtils.isEmpty(stockList)){
//            throw new BizException("库存未初始化！");
//        }
//
//        if (stockList.size() != productIds.size()){
//            throw new BizException("部分商品库存未初始化！");
//        }

        // 扣减库存
        for (CartProductDto cartProductDto : dtoList){
            //根据这两个进行库存的扣减
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            //productNum不能超出我们限购的数量

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);

            stockMapper.updateStock(stock);

        }

        return true;
    }
}
